<?php

namespace App\Http\Controllers\RESTfulApi\v1;

use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

use Tymon\JWTAuth\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;

//use App\Utils\Responser;
use App\Services\AuthService;
//use App\Events\LoginEvent;
//use Jenssegers\Agent\Agent;

class AuthController extends Controller
{
    protected $auth, $authService;
    protected $admin;
    public function __construct(JWTAuth $auth)
    {
        $this->auth = $auth;
        $this->authService = new AuthService;
        // $this->admin = $admin;
    }
    #登录
    public function authLogin(Request $request)
    {
        $params = $request->params;

        try {
            $admin_data = $this->authService->get_admin_info($params['username'], $params['password']);
            #生成token
            $token = $this->auth->fromUser($admin_data);
            // dd($token);
            #启动监听器
            event(new LoginEvent($admin_data, new Agent(), \Request::getClientIp(), time()));
            return Responser::success([
                'token' => $token,
                'expires_in' => $this->auth->factory()->getTTL() * 60,
                'userinfo' => $admin_data->toArray()
            ]);
        }catch (\Exception $e) {
            return Responser::error($e->getMessage());
        }
    }

    #刷新令牌，使当前无效
    public function refresh_token(Request $request)
    {
        $params = $request->params;
        try {
            $token = $this->auth->getToken()->get();//验证是否能获取到token
            $newToken = auth()->refresh();
            return Responser::success([
                'newtoken' => $newToken,
                'expires_in' => $this->auth->factory()->getTTL() * 60
            ]);
        }catch (\Exception $e) {
            return Responser::error($e->getMessage());
        }
    }
    /**
     * 退出登录
     *
     * Undocumented function long description
     *
     * @param Type $var Description
     * @return type
     * @throws conditon
     **/
    public function login_out(Request $request)
    {
        try {
            $token = $this->auth->getToken()->get();
            $result = $this->auth->invalidate();
            return Responser::success();
        }catch (\Exception $e) {
            return Responser::error($e->getMessage());
        }
    }
}